package com.example.everying.utils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: everything
 * @description: 随机数生成类
 * @author: zw
 * @create: 2025-05-15 15:21
 **/

public class RandomUtil {

    private static final Random RANDOM = new Random();
    private static final int RANDOM_NUMBER_LENGTH = 4;
    private static final int MAX_RANDOM_NUMBER = (int) Math.pow(10, RANDOM_NUMBER_LENGTH);
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyMMddHHmm");

    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";
    private static final int NAME_LENGTH = 8;
    private static final int MAX_ATTEMPTS = 1000;
    private static Set<String> existingNames = new HashSet<>();

    public static synchronized String generateId() {
        // 生成6位随机数（不足4位前补0）
        String randomPart = String.format("%04d", RANDOM.nextInt(MAX_RANDOM_NUMBER));

        // 获取当前时间戳（格式：yyMMddHHmm）
        String timePart = DATE_FORMAT.format(new Date());

        // 组合ID：4位随机数 + 10位时间戳
        return randomPart + timePart;
    }

    public static synchronized String generateName(){
        Random random = new Random();
        String userName;
        int attempts = 0;

        do {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < NAME_LENGTH; i++) {
                int index = random.nextInt(CHARACTERS.length());
                sb.append(CHARACTERS.charAt(index));
            }
            userName = sb.toString();
            attempts++;
        } while (existingNames.contains(userName) && attempts < MAX_ATTEMPTS);

        if (attempts == MAX_ATTEMPTS) {
            throw new RuntimeException("Failed to generate a unique username after " + attempts + " attempts.");
        }

        existingNames.add(userName);
        return userName;

    }

    public static void main(String[] args) {
        System.out.println(generateName());
        System.out.println(generateId());;
    }
}
